package com.banzhi.shop.activity;

import android.Manifest;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.banzhi.shop.MyApp;
import com.banzhi.shop.R;
import com.banzhi.shop.adapter.InnerFragmentPagerAdapter;
import com.banzhi.shop.base.BaseActivity;
import com.banzhi.shop.entity.Setting.Setting_Data;
import com.banzhi.shop.fragment.CollegeFragment;
import com.banzhi.shop.fragment.HomeFrg;
import com.banzhi.shop.fragment.MyFrg;
import com.banzhi.shop.fragment.StoreFrg;
import com.banzhi.shop.fragment.TeMaiFrg;
import com.banzhi.shop.model.CallBack.SettingCallBack;
import com.banzhi.shop.model.ISettingModel;
import com.banzhi.shop.model.Impl.SettingImpl;
import com.banzhi.shop.qimo.View.PeerDialog;
import com.banzhi.shop.qimo.activity.ChatActivity;
import com.banzhi.shop.service.DownloadService;
import com.banzhi.shop.utils.ASUtils;
import com.banzhi.shop.utils.LoadingDialogUtils;
import com.banzhi.shop.utils.TemplatePopupwindowUtils;
import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.view.DragFloatActionButton;
import com.banzhi.shop.view.NoScrollViewPager;
import com.moor.imkf.GetPeersListener;
import com.moor.imkf.IMChatManager;
import com.moor.imkf.InitListener;
import com.moor.imkf.model.entity.Peer;
import com.moor.imkf.utils.NetUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import static com.banzhi.shop.MyApp.accessID;

/**
 * 主页面
 */
public class MainActivity extends BaseActivity implements View.OnClickListener, RadioGroup.OnCheckedChangeListener, SettingCallBack {
    private ISettingModel settingmodel;
    private NoScrollViewPager viewpager;
    public RadioGroup rgp_main;
    /**
     * 储存fragment的集合
     */
    private List<Fragment> fragmentlist;
    private InnerFragmentPagerAdapter adapter;
    private CollegeFragment collegeFragment;
    private DragFloatActionButton actionButton;
    private int type;
    private HomeFrg mHomeFrg;
    private RadioButton mGrouping;
    private RadioButton mRbStore;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        //注册
    //    EventBus.getDefault().register(this);

        initView();
        settingmodel = new SettingImpl();
        settingmodel.getData(this);
        int id = getIntent().getIntExtra("id", 0);
        //   LogUtils.e("Mainid-----", id + "");
        if (id == 4) {
            Fragment fragment = new MyFrg();
            FragmentManager supportFragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.rb_my, fragment);
            fragmentTransaction.commit();
            viewpager.setCurrentItem(4);
        }
    }

    private void initView() {
        actionButton = (DragFloatActionButton) findViewById(R.id.action_button);
        rgp_main = (RadioGroup) findViewById(R.id.rgp_main);
        mGrouping = (RadioButton) findViewById(R.id.rb_temai);
        mRbStore = (RadioButton) findViewById(R.id.rb_store);
        viewpager = (NoScrollViewPager) findViewById(R.id.viewpager);
        viewpager.setOffscreenPageLimit(5);
        collegeFragment = new CollegeFragment();
        mHomeFrg = new HomeFrg();
        TeMaiFrg teMaiFrg = new TeMaiFrg();
        StoreFrg storeFrg = new StoreFrg();

        fragmentlist = new ArrayList<>();
        fragmentlist.add(new HomeFrg());
        fragmentlist.add(new TeMaiFrg());
        fragmentlist.add(collegeFragment);
        fragmentlist.add(new StoreFrg());
        fragmentlist.add(new MyFrg());

        // 为ViewPager设置Adapter;
        adapter = new InnerFragmentPagerAdapter(getSupportFragmentManager(), fragmentlist);
        viewpager.setAdapter(adapter);
        rgp_main.setOnCheckedChangeListener(this);
        actionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //判断版本若为6.0申请权限
                if (Build.VERSION.SDK_INT < 23) {
                    init();
                } else {
                    //6.0
                    if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
                        //该权限已经有了
                        //适配小米机型
                        AppOpsManager appOpsManager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
                        int checkOp = appOpsManager.checkOp(AppOpsManager.OPSTR_READ_PHONE_STATE, Binder.getCallingUid(), getPackageName());
                        if (checkOp != AppOpsManager.MODE_ALLOWED) {
                            TemplatePopupwindowUtils.showPermissionsPopupWindow(MainActivity.this, "为了能够正常使用客服功能", "请开启获取手机信息权限");
                        } else {
                            //获取权限后的操作
                            init();
                        }
                    } else {
                        //申请该权限
                        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_PHONE_STATE}, 0x1111);
                    }
                }
            }
        });
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.rb_home://首页
                viewpager.setCurrentItem(0, false);
                break;
            case R.id.rb_temai://拼团
                viewpager.setCurrentItem(1, false);
                break;
            case R.id.rb_college://学院
                viewpager.setCurrentItem(2, false);

                break;
            case R.id.rb_store://店铺
                viewpager.setCurrentItem(3, false);
                break;
            case R.id.rb_my://我的
                viewpager.setCurrentItem(4, false);
                break;

        }

    }

    private long lastClickTime = 0;

    //解决CollegeFragment中WebView浏览器回退网页而不是退出，需要在当前Activity中处理并重写该back事件；
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //&& viewpager.getCurrentItem()== 2
            if (viewpager.getCurrentItem() == 2) {
                //    Log.d("LIJIE", "是否是web fragment－－－－0");
                boolean isCanBack = ((CollegeFragment) collegeFragment).onKeyDown(keyCode, event);
                if (!isCanBack) {
                    doAppFinish();
                }
                return true;
            } else {
                doAppFinish();
            }

        }
        return super.onKeyDown(keyCode, event);
    }

    private void doAppFinish() {


        //用户在按返回键的时候你并不希望退出（默认就finish了），而是只希望置后台，就可以调这个方法(回到原来的页面)
        moveTaskToBack(true);

        //finish();
        // System.exit(0);

    }

    private Setting_Data setting;
    private PopupWindow popWindow;

    @Override
    public void onsettingSuccess(Object object) {
        setting = (Setting_Data) object;
        if (!ASUtils.getVersionName(this).equals(setting.getAPP_VERSION())) {
            if (!MyApp.IsCheck) {
                popupwindow(setting.getANDROID_URL());
            } else {
                ToastUtils.makeToastShort("正在更新中");
            }
        }
        initData();
    }

    private void initData() {
        if ("1".equals(MyApp.loginMessage.getString("isagent",""))) {
            mRbStore.setVisibility(View.VISIBLE);
        }else {
            mRbStore.setVisibility(View.GONE);
        }
    }

    @Override
    public void onsettingError(Object object) {

    }

    /**
     * 版本更新
     */
    private void popupwindow(final String str) {
        View contentView = LayoutInflater.from(this).inflate(R.layout.popupwindow_updating, null);
        popWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popWindow.setContentView(contentView);
        popWindow.setAnimationStyle(R.style.AnimBottom);

        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(false);// 设置允许在外点击消失
        //设置各个控件的点击响应
        TextView tv1 = (TextView) contentView.findViewById(R.id.tv_know);
        TextView tv2 = (TextView) contentView.findViewById(R.id.tv_copy);
        RelativeLayout rlbackground = (RelativeLayout) contentView.findViewById(R.id.rl_background);
        LinearLayout ll = (LinearLayout) contentView.findViewById(R.id.ll);
        rlbackground.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        tv1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        tv2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {


                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1000);
                } else {
                    MyApp.IsCheck = true;
                    Intent inetent = new Intent(MainActivity.this, DownloadService.class);
                    inetent.putExtra("downloadUrl", str);
                    startService(inetent);
                    ToastUtils.makeToastLong("正在下载更新中，请稍后");
                    popWindow.dismiss();
                }
            }
        });
        //显示PopupWindow
        View rootview = LayoutInflater.from(this).inflate(R.layout.activity_main, null);
        popWindow.showAtLocation(contentView, Gravity.CENTER, 0, 0);
    }

    //Android6.0申请权限的回调方法
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case 1000:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    MyApp.IsCheck = true;
                    Intent inetent = new Intent(MainActivity.this, DownloadService.class);
                    inetent.putExtra("downloadUrl", setting.getANDROID_URL());
                    startService(inetent);
                    ToastUtils.makeToastLong("正在下载更新中，请稍后");
                    popWindow.dismiss();
                } else {
                    TemplatePopupwindowUtils.showPermissionsPopupWindow(MainActivity.this, "为了能够正常更新版本", "请开启读取文件权限");
                }
            case 0x1111:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    init();
                } else {
                    TemplatePopupwindowUtils.showPermissionsPopupWindow(MainActivity.this, "为了能够正常使用客服功能", "请开启获取手机信息权限");
                }
                break;
        }
    }

    private void init() {

        if (!NetUtils.hasDataConnection(MainActivity.this)) {
            Toast.makeText(MainActivity.this, "当前没有网络连接", Toast.LENGTH_SHORT).show();
            return;
        }
        LoadingDialogUtils.showProgress(this);
        if (MyApp.isKFSDK) {
            LoadingDialogUtils.dismiss();
            getPeers();
        } else {
            startKFService();
        }
    }

    private void getPeers() {
        IMChatManager.getInstance().getPeers(new GetPeersListener() {
            @Override
            public void onSuccess(List<Peer> peers) {
                System.out.println("获取技能组成功");
                if (peers.size() > 1) {
                    PeerDialog dialog = new PeerDialog();
                    Bundle b = new Bundle();
                    b.putSerializable("Peers", (Serializable) peers);
                    b.putString("type", "init");
                    dialog.setArguments(b);
                    dialog.show(getFragmentManager(), "");

                } else if (peers.size() == 1) {
                    startChatActivity(peers.get(0).getId());
                } else {
                    startChatActivity("");
                }
            }

            @Override
            public void onFailed() {
                System.out.println("获取技能组失败了");
            }
        });
    }

    private void startKFService() {
        new Thread() {
            @Override
            public void run() {
                IMChatManager.getInstance().setOnInitListener(new InitListener() {
                    @Override
                    public void oninitSuccess() {
                        MyApp.isKFSDK = true;
                        LoadingDialogUtils.dismiss();
                        getPeers();
                        Log.d("MobileApplication", "sdk初始化成功");
                    }

                    @Override
                    public void onInitFailed() {
                        MyApp.isKFSDK = false;
                        LoadingDialogUtils.dismiss();
                        Toast.makeText(MainActivity.this, "客服初始化失败", Toast.LENGTH_SHORT).show();
                        Log.d("MobileApplication", "sdk初始化失败, 请填写正确的accessid");
                    }
                });
                //初始化IMSdk,填入相关参数
                IMChatManager.getInstance().init(MyApp.getInstance(), "action", accessID, MyApp.loginMessage.getString("mobile", ""), MyApp.loginMessage.getString("mobile", ""));
            }
        }.start();
    }

    private void startChatActivity(String peerId) {
        Intent chatIntent = new Intent(MainActivity.this, ChatActivity.class);
        chatIntent.putExtra("PeerId", peerId);
        startActivity(chatIntent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
   //     EventBus.getDefault().unregister(this);
    }

    private void getDialogPermission() {
        //Android6.0 + need require permission
        if (Build.VERSION.SDK_INT >= 23) {
            if (!Settings.canDrawOverlays(this)) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                startActivity(intent);
                return;
            }
        }
    }



}

